package com.wechat.service.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;


/**
 * http 请求工具类
 * @author xiapeng
 *
 */
public class HttpUtil {
	
	/**
	 * http get请求
	 * @param baseUrl
	 * @return
	 * @throws IOException 
	 */
	public static String dohttpGetRequest(String baseUrl) throws IOException{
		return dohttp(baseUrl,"","GET");
	}
	/**
	 * http post请求
	 * @param baseUrl
	 * @param param
	 * @return
	 * @throws IOException
	 */
	public static String dohttpPostRequest(String baseUrl,Map<String, String> param) throws IOException{
		return dohttp(baseUrl,createQueryParam(param),"POST");
	}
	
	
	private static String createQueryParam(Map<String,String> requestParam) {
		StringBuffer param = new StringBuffer();
		Set<Entry<String,String>> set = requestParam.entrySet();
		Iterator<Entry<String,String>> it = set.iterator();
		while(it.hasNext()) {
			Entry<String,String> entry = it.next();
			param.append(entry.getKey());
			param.append("=");
			param.append(entry.getValue());
			if (it.hasNext()) {
				param.append("&");
			}
		}
		return param.toString();
	}
	
	private static String dohttp(String baseUrl,String paramString,String requestMethod) 
			throws IOException{
		StringBuffer resultStrBuf = new StringBuffer();
	
		URL url = new URL(baseUrl);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		conn.setRequestMethod(requestMethod);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setUseCaches(false); 
		conn.setInstanceFollowRedirects(false);
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
		conn.setRequestProperty("Accept-Charset", "utf-8");
		
		DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
		byte[] paramBytes = paramString.getBytes("utf-8");
		dos.write(paramBytes);
		dos.flush();
		
		conn.connect();
		int responseCode = conn.getResponseCode();
		if (responseCode == 200) {
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
			String line = "";
			while(null != (line=br.readLine())){
				resultStrBuf.append(line);
            }
		}else{
			resultStrBuf.append("{\"status\":"+responseCode+"}");
		}
		conn.disconnect();
		dos.close();
		return resultStrBuf.toString();
	}
}
